<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Models\Coin;
use App\Http\Controllers\Controller;

class CoinsController extends Controller
{
    /**
     * 获取充值列表
     *
     * @return array
     */
    public function index()
    {
        $coins = Coin::orderByDesc('stick_time')->orderByDesc('id')->get();

        $data = $coins->map(function ($coin) {
            return [
                'id' => $coin->id,
                'coin' => $coin->coin,
                'coin_award' => $coin->coin_award,
                'money' => $coin->money,
                'status' => $coin->status,
                'stick_time' => $coin->stick_time,
            ];
        });

        return $this->wrapData($data);
    }

    /**
     * 更新充值项
     *
     * @param Request $request
     * @param Coin $coin
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(Request $request, Coin $coin)
    {
        $inputs = $this->validate($request, [
            'coin' => 'required|integer|between:1,10000',
            'coin_award' => 'integer|between:0,10000',
            'money' => 'required|numeric|between:0.01,10000',
            'is_top' => 'in:0,1',
            'status' => 'in:-1,1',
        ]);

        if (Coin::STATUS_DISABLE == $request->post('status')) {
            if (Coin::where('status', Coin::STATUS_ENABLE)->count() <= 2) {
                return invalidation('显示的充值项不能少于两条');
            }
        }

        if (isset($inputs['is_top']) && $inputs['is_top'] == 1) {
            $inputs['stick_time'] = time();
            unset($inputs['is_top']);
        }

        $coin->update($inputs);
    }
}
